﻿package  {
	import flash.display.MovieClip;
	import flash.events.Event;
	
	public class Monkey extends MovieClip{
		private var currentX:uint;
		private var currentY:uint;
		
		private var walkArr:Array;
		private var frameCount:uint;
		
		public function Monkey() {
			this.mouseEnabled = false;
			MainPanel.monkeyWalkFlag = false;
			
			this.addEventListener(GameEvent.MonkeyMove, monkeyMoveHandler);//主角行走事件
			
			this.addEventListener(Event.REMOVED_FROM_STAGE, removeHandler);
		}
		
		private function removeHandler(e:Event):void{
			this.removeEventListener(GameEvent.MonkeyMove, monkeyMoveHandler);
			
			this.removeEventListener(Event.REMOVED_FROM_STAGE, removeHandler);
		}
		
		public function setPosition(point:Array):void{
			if(point.length < 2)return;
			
			this.currentX = uint(point[0]);
			this.currentY = uint(point[1]);
		}
		
		public function getCurrentX():uint{
			return this.currentX;
		}
		
		public function getCurrentY():uint{
			return this.currentY;
		}
		
		//主角行走事件
		private function monkeyMoveHandler(e:GameEvent):void{
			var tmpArr:Array = e.params as Array;
			
			//行走坐标
			this.walkArr = tmpArr[0];
			frameCount = 4;
			MainPanel.monkeyWalkFlag = true;
			this.addEventListener(Event.ENTER_FRAME, walkAnimationHandler);
		}
		
		private function walkAnimationHandler(e:Event):void{
			if(frameCount == 4){
				this.x = (this.currentX + 0.5) * MainPanel.cellWidth;
				this.y = (this.currentY + 0.5) * MainPanel.cellWidth;
				
				if(this.walkArr.length == 0){
					this.gotoAndStop("stay");
					MainPanel.monkeyWalkFlag = false;
					
					this.parent.parent.dispatchEvent(new GameEvent(GameEvent.ElementsDrop));
					this.removeEventListener(Event.ENTER_FRAME, walkAnimationHandler);
					return;
				}
				
				var tmpPoint = this.walkArr.shift();
				if(tmpPoint.length < 2)return;
			
				//根据坐标判断前进方向
				if(tmpPoint[0] == this.currentX){
					if(tmpPoint[1] < this.currentY){
						//up
						this.gotoAndPlay("toUp");
					}
					else{
						//down
						this.gotoAndPlay("toDown");
					}
				}
				else{
					//ahead
					this.gotoAndPlay("toRight");
				}
				frameCount = 0;
				this.currentX = tmpPoint[0];
				this.currentY = tmpPoint[1];
				//触发设置以主角为中心的bgMc的坐标事件
				this.parent.parent.dispatchEvent(new GameEvent(GameEvent.BgMcMove));
			}
			frameCount ++;
		}

	}
	
}
